using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class DialogueManager : Singleton<DialogueManager>
{
    public static event Action<InteractionType> OnExtraInteractionEvent; 
    
    [Header("配置")]
    [SerializeField] private GameObject dialoguePanel;
    [SerializeField] private Image npcIcon;
    [SerializeField] private TextMeshProUGUI npcNameTMP;
    [SerializeField] private TextMeshProUGUI npcDialogueTMP;
    
    public NPCInteraction NPCSelected { get; set; }

    private bool dialogueStated;
    private PlayerActions actions;
    private Queue<string> dialogueqQueue = new Queue<string>();

    protected override void Awake()
    {
        base.Awake();
        actions = new PlayerActions();
    }

    private void OnEnable()
    {
        actions.Enable();
    }

    private void OnDisable()
    {
        actions.Disable();
    }

    private void Start()
    {
        actions.Dialogue.Interact.performed += ctx => ShowDialogue();
        actions.Dialogue.Continue.performed += ctx => ContinueDialogue();
    }
    
    public void ShowDialogue()
    {
        if (NPCSelected == null)
        {
            return;
        }

        if (dialogueStated)
        {
            return;
        }
        dialoguePanel.SetActive(true);
        LoadDialogueFromNPC();
        npcIcon.sprite = NPCSelected.DialogueToShow.Icon;
        npcNameTMP.text = NPCSelected.DialogueToShow.Name;
        npcDialogueTMP.text = NPCSelected.DialogueToShow.Greeting;
        dialogueStated = true;
    }
    
    public void ContinueDialogue()
    {
        if (NPCSelected == null)
        {
            dialogueqQueue.Clear();
            return;
        }

        if (dialogueqQueue.Count <= 0)
        {
            CloseDialoguePanel();
            dialogueStated = false;
            if (NPCSelected.DialogueToShow.HasInteraction)
            {
                OnExtraInteractionEvent?.Invoke(NPCSelected.DialogueToShow.InteractionType);
            }
            return;
        }
        
        npcDialogueTMP.text = dialogueqQueue.Dequeue();
    }

    public void CloseDialoguePanel()
    {
        dialoguePanel.SetActive(false);
        dialogueStated = false;
        dialogueqQueue.Clear();
    }

    private void LoadDialogueFromNPC()
    {
        if (NPCSelected.DialogueToShow.Dialogue.Length <= 0)
        {
            return;
        }

        foreach (string sentence in NPCSelected.DialogueToShow.Dialogue)
        {
            dialogueqQueue.Enqueue(sentence);
        }
    }
}
